package com.linux.huhx.business.service;

import java.util.Map;

import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * 注册的服务类
 * 
 * @author huhx
 * @date: 2016年12月18日 上午11:56:57
 */
@Service
public class RegisterService {
	private static Logger logger = LoggerFactory.getLogger(RegisterService.class);
	@Resource
	private SqlSessionTemplate sqlSessionTemplate;

	@Resource
	private TransactionTemplate transactionTemplate;

	// 检查邮箱是否存在
	public boolean checkEmailExist(String email) {
		Map<String, String> userMap = sqlSessionTemplate.selectOne("register.queryUserEmailExist", email);
		logger.info("check email map: " + userMap);
		if (userMap == null || userMap.size() < 1) {
			return false;
		}
		return true;
	}

	// 保存用户的信息
	public void saveUserInfo(final Map<String, Object> map) {
		transactionTemplate.execute(status -> {
            // 影响的行数，返回的自增长id存在于map中
            int effectCount = sqlSessionTemplate.insert("register.insertUserInfo", map);
            long userId = (Long) map.get("userId");
            logger.info("save user info effectCount: " + effectCount + ", userId: " + userId);
            // 这里会插入一条登录的信息
            sqlSessionTemplate.insert("register.insertLoginInfo", userId);
            return null;
        });
	}

	// 根据邮箱查询出用户的主键id
	public Long queryUserIdByEmail(String email) {
		Map<String, Long> userMap = this.sqlSessionTemplate.selectOne("login.queryUserEmailExist", email);
		if (userMap == null || userMap.size() < 1) {
			return null;
		}
		return userMap.get("UserId");
	}
}
